<?php


function _refix_ali_imgurl($url)
{
	if(strstr($url,"ae01.alicdn.com"))
	{
		$url = str_replace("ae01.alicdn.com","picture.qdbeauty.com",$url);

	    if(strstr($url,"_640x640"))
	    {
	        $tmp=explode("_640x640",$url);
	        $url=$tmp[0];
	    }
	}
    
    return $url;
}

/*
error_reporting(0);
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
    throw new Exception("$errno,$errmsg",1);
}
$old_error_handle = set_error_handler("userErrorHandler");
*/
    $csvfilename="upload/csv/shopify_{$id}_".date("mdHi").".csv";

    $csvtitle=array(
    'Handle',
    'Title',
    'Body (HTML)',
    'Vendor',
    'Type',
    'Tags',
    'Published',
    'Option1 Name',
    'Option1 Value',
    'Option2 Name',
    'Option2 Value',
    'Option3 Name',
    'Option3 Value',
    'Variant SKU',
    'Variant Grams',
    'Variant Inventory Tracker',
    'Variant Inventory Qty',
    'Variant Inventory Policy',
    'Variant Fulfillment Service',
    'Variant Price',
    'Variant Compare At Price',
    'Variant Requires Shipping',
    'Variant Taxable',
    'Variant Barcode',
    'Image Src',
    'Image Alt Text',
    'Gift Card',
    'Google Shopping / MPN',
    'Google Shopping / Age Group',
    'Google Shopping / Gender',
    'Google Shopping / Google Product Category',
    'SEO Title',
    'SEO Description',
    'Google Shopping / AdWords Grouping',
    'Google Shopping / AdWords Labels',
    'Google Shopping / Condition',
    'Google Shopping / Custom Product',
    'Google Shopping / Custom Label 0',
    'Google Shopping / Custom Label 1',
    'Google Shopping / Custom Label 2',
    'Google Shopping / Custom Label 3',
    'Google Shopping / Custom Label 4',
    'Variant Image',
    'Variant Weight Unit'
    );
    //$tr = new TranslateClient(null, "en");

    $this->parsecsv->save($csvfilename,[], false,$csvtitle);
    $csv_export=array();
    foreach($products as $p){
        

        try{
            $option=unserialize($p["option"]);
        }
        catch (Exception $e) {
           continue;
        }


        $imglist=unserialize($p["thumb"]);
        if(empty($imglist))
        {
            if(isset($option["vv"][0]["image"]))
            {
                $imglist=[$option["vv"][0]["image"][0]];
            }
            else
            {
                continue;
            }
        }
        $p["name"]=$this->refixtitle($p["name"]);
        
        foreach($imglist as &$imgurl)
        {
            $imgurl=_refix_ali_imgurl($imgurl);
            //$imgurl=str_replace("ae01.alicdn.com","picture.qdbeauty.com",$imgurl);
        }
        /*
        if(count($imglist)>1)
        {
            $tmp=$imglist[1];
            $imglist[1]=$imglist[0];
            $imglist[0]=$tmp;
        }
        */

        if($p["tags"])
        {
            $tagstring=substr(rtrim($p["tags"],","),0,200);
            $tmp_tag=explode(",",$tagstring);
            array_pop($tmp_tag);
            $newtag=[];
            foreach($tmp_tag as $tag)
            {
                $tag=str_replace(["-","%","&","#"],"",$tag);
                
                if(empty(trim($tag))) continue;
                if(strstr($tag,"#")) continue;
                if(strstr($tag,"M/L/")) continue;
                if(strstr($tag,"M/L/")) continue;
                if(preg_match('/china/i',$tag)) continue;
                if(!in_array($tag,$newtag)) $newtag[]=$tag;
            }
            $tags=implode(",",$newtag);
        }
        else
        {
            $tags="";
        }
        
        



        if(empty(trim(strip_tags($p["desc"]))))
        {
            $p["desc"]="<h5>".$p["name"]."</h5>".$p["desc"];
        }

        if(empty($p["meta"]))
        {
            $p["meta"]=$p["name"];
        }

        $p["name"]=$this->refixtitle($p["name"]);
        //echo $p["name"];
        //die();
        //$urlhanle=$tr->translate($p["name"]);
        $urlhanle=strtolower($p["name"]);
        $handle=$p['id']."_".str_replace(" ","_",$urlhanle);
        
        $value1_num=$value2_num=$value3_num=0;
        if(isset($option["vv"])){
          $option_num=count($option["vv"]);
        }else{
            $option_num=0;
        }
        if($option_num>3) $option_num=3;
        if ($option_num>0) {
            $value1_num=count($option["vv"][0]["value"]);
        }
        if ($option_num>1) {
            $value2_num=count($option["vv"][1]["value"]);
        }
        if ($option_num>2) {
            $value3_num=count($option["vv"][2]["value"]);
        }
        switch($option_num){
            case 0:
                $total_option_row=0;
                $title1="Title";
                $value1="Default Title";
                $title2=$title3="";
                $value2=$value3="";
                $vaimg="";
                break;
            case 1:
                $total_option_row=$value1_num;
                $title1=$option["vv"][0]["name"];
                $value1=$option["vv"][0]["value"][0];
                if(isset($option["vv"][0]["image"][0])){
                    $vaimg=$option["vv"][0]["image"][0];
                }else{
                    if($imglist)
                    {
                        $randkey=array_rand($imglist);
                        $vaimg=$imglist[$randkey];
                    }
                    else
                    {
                        $vaimg="";
                    }
                    
                }
                $title2=$title3="";
                $value2=$value3="";
                break;
            case 2:
                $total_option_row=$value1_num*$value2_num;
                $title1=$option["vv"][0]["name"];
                $title2=$option["vv"][1]["name"];
                $value1=$option["vv"][0]["value"][0];
                $value2=$option["vv"][1]["value"][0];
                if(isset($option["vv"][0]["image"][0])){
                    $vaimg=$option["vv"][0]["image"][0];
                }else if(isset($option["vv"][1]["image"][0])){
                    $vaimg=$option["vv"][1]["image"][0];
                }else{
                    if($imglist)
                    {
                        $randkey=array_rand($imglist);
                        $vaimg=$imglist[$randkey];
                    }
                    else
                    {
                        $vaimg="";
                    }
                }
                $title3="";
                $value3="";
                break;
            case 3:
                $total_option_row=$value1_num*$value2_num*$value3_num;
                $title1=$option["vv"][0]["name"];
                $title2=$option["vv"][1]["name"];
                $title3=$option["vv"][2]["name"];
                $value1=$option["vv"][0]["value"][0];
                $value2=$option["vv"][1]["value"][0];
                $value3=$option["vv"][2]["value"][0];
                if(isset($option["vv"][0]["image"][0])){
                    $vaimg=$option["vv"][0]["image"][0];
                }else if(isset($option["vv"][1]["image"][0])){
                    $vaimg=$option["vv"][1]["image"][0];
                }else if(isset($option["vv"][2]["image"][0])){
                    $vaimg=$option["vv"][2]["image"][0];
                }else{
                    if($imglist)
                    {
                        $randkey=array_rand($imglist);
                        $vaimg=$imglist[$randkey];
                    }
                    else
                    {
                        $vaimg="";
                    }
                }
                break;
        }
        if($vaimg){
            $vaimg=tomedia($vaimg);
            $vaimg=_refix_ali_imgurl($vaimg);
        }
        //print_r($option);
        //print_r($p);
        //die();
        if($option_num!=0 && isset($option["vv"][0]["price"][0])){
            //$price=$option["vc"][0];
            $price=$option["vv"][0]["price"][0];
        }else{
            $price=$p['price'];
        }

        $price=get_price($price_muti,$price);
        $compare_ratio=[1.3,1.35,1.4,1.45,1.5,1.55,1.6,1.65,1.7];
        shuffle($compare_ratio);
        $compareprice=sprintf("%.2f",$price*$compare_ratio[0]);

        $csv_export[]=array(
            $handle,
            $p['name'],
            $p['desc'],
            $vendor,
            $type,
            $tags,
            'TRUE',
            $title1,
            $value1,
            $title2,
            $value2,
            $title3,
            $value3,
            $prefix.$p['id']."_0",
            '0',
            '',
            50,
            'deny',
            'manual',
            $price,
            $compareprice,
            '',
            '',
            '',
            tomedia($imglist[0]),
            $p['name']." img 1",
            'FALSE',
            '',
            '',
            '',
            '',
            $p['name'],
            $p["meta"],
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            $vaimg,
            ''
        );


        if (count($imglist)>1 && $total_option_row<=1) {
            unset($imglist[0]);
            foreach($imglist as $img){
                $csv_export[]=array(
                    $handle,
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    tomedia($img),
                    $p['name']." img",
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    '',
                    ''
                );
            }
        } else if ($total_option_row>1){
            $opcount=1;
            switch($option_num){
                case 1:
                    $opttcount=0;
                    foreach($option["vv"][0]["value"] as $k=>$rrow1){
                        $opttcount++;
                        if($opttcount==1) continue;
                        if(isset($imglist[$opcount])){
                            $img=$imglist[$opcount];
                            $imgdesc=$p['name']." img ".$opcount;
                        }else{
                            $img=$imgdesc="";
                        }

                        if(isset($option["vv"][0]["image"][$k])){
                            $vaimg=$option["vv"][0]["image"][$k];
                        }else{
                            if($imglist)
                            {
                                $randkey=array_rand($imglist);
                                $vaimg=$imglist[$randkey];
                            }
                            else
                            {
                                $vaimg="";
                            }
                        }
                        if($vaimg){
                            $vaimg=tomedia($vaimg);
                            $vaimg=_refix_ali_imgurl($vaimg);
                        }
                        if(isset($option["vv"][0]["price"][$k]) && $option["vv"][0]["price"][$k])
                        {
                           
                            $price=$option["vv"][0]["price"][$k];
                        }
                        else
                        {
                            $price=$p['price'];
                        }
                        $price=get_price($price_muti,$price);                    
                        $compareprice=sprintf("%.2f",$price*$compare_ratio[0]);
                        
                        $csv_export[]=array(
                            $handle,
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            $rrow1,
                            '',
                            '',
                            '',
                            '',
                            $prefix.$p['id']."_".$opcount,
                            '0',
                            '',
                            50,
                            'deny',
                            'manual',
                            $price,
                            $compareprice,
                            '',
                            '',
                            '',
                            tomedia($img),
                            $imgdesc,
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            '',
                            $vaimg,
                            ''
                        );
                        $opcount++;
                    }
                    break;
                case 2:
                    $opttcount=0;
                    foreach($option["vv"][0]["value"] as $k=>$rrow1){
                        if(strstr(strtolower($rrow1),"as pic"))
                        {
                            $rrow1.="_".$k;
                        }
                        foreach($option["vv"][1]["value"] as $j=>$rrow2){
                            $opttcount++;
                            if(strstr(strtolower($rrow2),"as pic"))
                            {
                                $rrow2.="_".$j;
                            }
                            if($opttcount==1) continue;
                            if($opcount>=99) continue;
                            if(isset($imglist[$opcount])){
                                $img=$imglist[$opcount];
                                $imgdesc=$p['name']." img ".$opcount;
                            }else{
                                $img=$imgdesc="";
                            }
                            if(isset($option["vv"][0]["image"][$k])){
                                $vaimg=$option["vv"][0]["image"][$k];
                            }else if(isset($option["vv"][1]["image"][$j])){
                                $vaimg=$option["vv"][1]["image"][$j];
                            }else{
                                if($imglist)
                                {
                                    $randkey=array_rand($imglist);
                                    $vaimg=$imglist[$randkey];
                                }
                                else
                                {
                                    $vaimg="";
                                }
                            }
                            if($vaimg){
                                $vaimg=tomedia($vaimg);
                                $vaimg=_refix_ali_imgurl($vaimg);
                            }


                            if(isset($option["vv"][0]["price"][$k]) && $option["vv"][0]["price"][$k])
                            {
                               
                                $price=$option["vv"][0]["price"][$k];
                            }
                            else
                            {
                                $price=$p['price'];
                            }
                            $price=get_price($price_muti,$price);                    
                            $compareprice=sprintf("%.2f",$price*$compare_ratio[0]);
                            
                            
                            $csv_export[]=array(
                                $handle,
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                $rrow1,
                                '',
                                $rrow2,
                                '',
                                '',
                                $prefix.$p['id']."_".$opcount,
                                '0',
                                '',
                                50,
                                'deny',
                                'manual',
                                $price,
                                $compareprice,
                                '',
                                '',
                                '',
                                tomedia($img),
                                $imgdesc,
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                '',
                                $vaimg,
                                ''
                            );
                            $opcount++;
                        }
                    }
                    break;
                case 3:
                    $opttcount=0;
                    foreach($option["vv"][0]["value"] as $k=>$rrow1){
                        foreach($option["vv"][1]["value"] as $j=>$rrow2){        
                            foreach($option["vv"][2]["value"] as $m=>$rrow3){
                                $opttcount++;
                                if($opttcount==1) continue;
                                if($opcount>=99) continue;
                                if(isset($imglist[$opcount])){
                                    $img=$imglist[$opcount];
                                    $imgdesc=$p['name']." img ".$opcount;
                                }else{
                                    $img=$imgdesc="";
                                }
                                if(isset($option["vv"][0]["image"][$k])){
                                    $vaimg=$option["vv"][0]["image"][$k];
                                }else if(isset($option["vv"][1]["image"][$j])){
                                    $vaimg=$option["vv"][1]["image"][$j];
                                }else if(isset($option["vv"][2]["image"][$m])){
                                    $vaimg=$option["vv"][2]["image"][$m];
                                }else{
                                    if($imglist)
                                    {
                                        $randkey=array_rand($imglist);
                                        $vaimg=$imglist[$randkey];
                                    }
                                    else
                                    {
                                        $vaimg="";
                                    }
                                }
                                if($vaimg){
                                    $vaimg=tomedia($vaimg);
                                    $vaimg=_refix_ali_imgurl($vaimg);
                                }
                                if(isset($option["vv"][0]["price"][$k]) && $option["vv"][0]["price"][$k])
                                {
                                   
                                    $price=$option["vv"][0]["price"][$k];
                                }
                                else
                                {
                                    $price=$p['price'];
                                }
                                $price=get_price($price_muti,$price);                    
                                $compareprice=sprintf("%.2f",$price*$compare_ratio[0]);
                                
                                $csv_export[]=array(
                                    $handle,
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    $rrow1,
                                    '',
                                    $rrow2,
                                    '',
                                    $rrow3,
                                    $prefix.$p['id']."_".$opcount,
                                    '0',
                                    '',
                                    50,
                                    'deny',
                                    'manual',
                                    $price,
                                    $compareprice,
                                    '',
                                    '',
                                    '',
                                    tomedia($img),
                                    $imgdesc,
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',
                                    $vaimg,
                                    ''
                                );
                                $opcount++;
                            }
                        }
                    }
                    break;
            }
        
        }

        $this->parsecsv->save($csvfilename, $csv_export, true,$csvtitle);
        $csv_export=[];
    }

    $zipfilename=$csvfilename.".zip";

    $zip = new ZipArchive();
    $zip->open($zipfilename,ZipArchive::CREATE);  
    $zip->addFile($csvfilename,basename($csvfilename));   
    $zip->close(); 

    echo "<a href='/".$csvfilename.".zip'>下载csv文件</a>";
    die();